﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DTO;

namespace DAO
{
    public class PayMoneyDAO
    {
        public int InsertPayMoney(PayMoneyDTO pmDto)
        {
            using (BookStoreEntities ent = new BookStoreEntities())
            {
                PhieuThuTien pmInt = new PhieuThuTien
                {
                    MaPhieuThu = pmDto.PayMoneyCode,
                    KhachHangID = pmDto.PayMoneyCustomerID,    
                    SoTienThu = pmDto.Money,
                    NgayThu = (DateTime) pmDto.PayMoneyCreateDate,
                    NguoiLap = pmDto.PayMoneyUserID,
                    GhiChu = pmDto.PayMoneyNote,
                    SuDung = true
                };

                if (ent.PhieuThuTiens.Count(t => t.PhieuThuID != null) > 0)
                {
                    pmInt.PhieuThuID = ent.PhieuThuTiens.Max(t => t.PhieuThuID) + 1;
                }
                else
                {
                    pmInt.PhieuThuID = 1;
                }

                ent.AddToPhieuThuTiens(pmInt);

                DocSequenceDAO docSeqDAO = new DocSequenceDAO();
                docSeqDAO.UpdateNextDocSequence(DocSequence.Payment.ToString());

                ent.SaveChanges();

                return pmInt.PhieuThuID;
            }
        }

        public bool UpdatePayMoney(PayMoneyDTO payDTO)
        {
            try
            {
                using (BookStoreEntities ent = new BookStoreEntities())
                {
                    PhieuThuTien payEnt = ent.PhieuThuTiens.FirstOrDefault(c => c.PhieuThuID == payDTO.PayMoneyID);

                    payEnt.GhiChu = payDTO.PayMoneyNote;
                    payEnt.SoTienThu = payEnt.SoTienThu + payDTO.Money;
                    payEnt.KhachHangID = payDTO.PayMoneyCustomerID;

                    ent.SaveChanges();

                    return true;
                }
            }
            catch
            {
                return false;
            }
        }

        public int GetTotalPay(int customerID, int month)
        {
            try
            {
                using (BookStoreEntities ent = new BookStoreEntities())
                {
                    int year = DateTime.Now.Year;
                    List<PhieuThuTien> ptts = ent.PhieuThuTiens.Where(c => c.KhachHangID == customerID && DateTime.Parse(c.NgayThu.ToString()).Month == month && DateTime.Parse(c.NgayThu.ToString()).Year == year).ToList();

                    int total = 0;

                    foreach (PhieuThuTien pt in ptts)
                    {
                        total += (int)pt.SoTienThu;
                    }

                    return total;
                }
            }
            catch
            {
                return 0;
            }
        }
    }
}
